package com.innovation.chengzhangriji.service;

import android.content.Intent;
import android.os.IBinder;

import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.Timeline;
import com.innovation.chengzhangriji.TimelineAudioUrl;
import com.innovation.chengzhangriji.TimelinePhotoUrl;
import com.innovation.chengzhangriji.TimelineVideoScreenshotUrl;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.TypeDataResponse;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.loopj.android.http.FileAsyncHttpResponseHandler;

import org.apache.http.Header;

import java.io.File;

public class DownloadTimelineResService extends BaseTimelineService {

    private boolean photoError;

    @Override
    protected void onTimelineStartCommand() {
        syncTimelineRes();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private Timeline queryUnSyncResTimeline(int babyID) {
        return DatabaseManager.getInstance(this).queryUnSyncResTimeline(babyID);
    }

    private void updateUnSyncResTimeline(String uuid) {
        DatabaseManager.getInstance(this).updateUnSyncResTimeline(uuid);
    }

    private void updateUnSyncResTimelineError(String uuid) {
        DatabaseManager.getInstance(this).updateUnSyncResTimelineError(uuid);
    }

    private TimelinePhotoUrl queryUnSyncTimelinePhotoUrl(String uuid) {
        return DatabaseManager.getInstance(this).queryUnSyncTimelinePhotoUrl(uuid);
    }

    private void updateUnSyncTimelinePhotoUrl(String url, String localUrl) {
        DatabaseManager.getInstance(this).updateUnSyncTimelinePhotoUrl(url, localUrl);
    }

    private void updateUnSyncTimelinePhotoUrlError(String url) {
        DatabaseManager.getInstance(this).updateUnSyncTimelinePhotoUrlError(url);
    }

    private TimelineAudioUrl queryUnSyncTimelineAudio(String uuid) {
        return DatabaseManager.getInstance(this).queryUnSyncTimelineAudio(uuid);
    }

    private TimelineVideoScreenshotUrl queryUnSyncTimelineVideo(String uuid) {
        return DatabaseManager.getInstance(this).queryUnSyncTimelineVideoScreenshot(uuid);
    }

    private void updateUnSyncTimelineAudioUrl(String url, String localUrl) {
        DatabaseManager.getInstance(this).updateUnSyncTimelineAudioUrl(url, localUrl);
    }

    private void updateUnSyncTimelineAudioError(String url) {
        DatabaseManager.getInstance(this).updateUnSyncTimelineAudioError(url);
    }

    private void updateUnSyncTimelineVideoScreenshotUrl(String url, String localUrl) {
        DatabaseManager.getInstance(this).updateUnSyncTimelineVideoScreenshotUrl(url, localUrl);
    }

    private void updateUnSyncTimelineVideoScreenshotUrlError(String url) {
        DatabaseManager.getInstance(this).updateUnSyncTimelineVideoScreenshotUrlError(url);
    }

    private void syncTimelineRes() {
        LoginInfo loginInfo = Config.getLoginInfo(this);
        if (loginInfo == null) {
            stopSelf();
            return;
        }

        Timeline timeline = queryUnSyncResTimeline(loginInfo.getBabyID());
        if (timeline == null) {
            stopSelf();
            return;
        }
        switch (timeline.getType()) {
            case TypeDataResponse.TYPE_PHOTO:
                photoError = false;
                syncTimelinePhoto(timeline.getUuid());
                break;
            case TypeDataResponse.TYPE_AUDIO:
                syncTimelineAudio(timeline.getUuid());
                break;
            case TypeDataResponse.TYPE_VIDEO:
                syncTimelineVideo(timeline.getUuid());
                break;
        }
    }

    private void syncTimelinePhoto(final String uuid) {
        TimelinePhotoUrl timelinePhotoUrl = queryUnSyncTimelinePhotoUrl(uuid);
        if (timelinePhotoUrl == null) {
            if (photoError) {
                updateUnSyncResTimelineError(uuid);
            } else {
                updateUnSyncResTimeline(uuid);
            }
            syncTimelineRes();
            return;
        }
        final String url = timelinePhotoUrl.getUrl();
        final String thumbUrl = Config.createSizeUrl(url, 480);
        final int number = timelinePhotoUrl.getNumber();
        Client.downloadFile(this, thumbUrl, new FileAsyncHttpResponseHandler(Config.createFile(this, Config.THUMB_PHOTO_DIR)) {

            @Override
            public void onStart() {
                syncPhotoStart();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, File file) {
                String localThumbUrl = file.getPath();
                updateUnSyncTimelinePhotoUrl(url, localThumbUrl);
                syncPhotoSuccess(uuid, url, localThumbUrl, number);
                syncTimelinePhoto(uuid);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) {
                updateUnSyncTimelinePhotoUrlError(url);
                photoError = true;
                syncPhotoFailure(throwable.getMessage());
                syncTimelinePhoto(uuid);
            }
        }, networkUnavailableSampleImpl());
    }

    private void syncTimelineAudio(final String uuid) {
        TimelineAudioUrl timelineAudioUrl = queryUnSyncTimelineAudio(uuid);
        if (timelineAudioUrl == null) {
            updateUnSyncResTimeline(uuid);
            syncTimelineRes();
            return;
        }

        final String url = timelineAudioUrl.getUrl();
        Client.downloadFile(this, url, new FileAsyncHttpResponseHandler(Config.createFile(this, Config.AUDIO_DIR)) {

            @Override
            public void onStart() {
                syncAudioStart();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, File file) {
                String localUrl = file.getPath();
                updateUnSyncTimelineAudioUrl(url, localUrl);
                updateUnSyncResTimeline(uuid);
                syncAudioSuccess(uuid, url, localUrl);
                syncTimelineRes();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) {
                updateUnSyncTimelineAudioError(url);
                updateUnSyncResTimelineError(uuid);
                syncAudioFailure(throwable.getMessage());
                syncTimelineRes();
            }
        }, networkUnavailableSampleImpl());
    }

    private void syncTimelineVideo(final String uuid) {
        TimelineVideoScreenshotUrl timelineVideoScreenshotUrl = queryUnSyncTimelineVideo(uuid);
        if (timelineVideoScreenshotUrl == null) {
            updateUnSyncResTimeline(uuid);
            syncTimelineRes();
            return;
        }

        final String url = timelineVideoScreenshotUrl.getUrl();
        final String thumbUrl = Config.createSizeUrl(url, 480);
        Client.downloadFile(this, thumbUrl, new FileAsyncHttpResponseHandler(Config.createFile(this, Config.SCREENSHOT_DIR)) {

            @Override
            public void onStart() {
                syncVideoScreenshotStart();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, File file) {
                String localUrl = file.getPath();
                updateUnSyncTimelineVideoScreenshotUrl(url, localUrl);
                updateUnSyncResTimeline(uuid);
                syncVideoScreenshotSuccess(uuid, url, localUrl);
                syncTimelineRes();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) {
                updateUnSyncTimelineVideoScreenshotUrlError(url);
                updateUnSyncResTimelineError(uuid);
                syncVideoScreenshotFailure(throwable.getMessage());
                syncTimelineRes();
            }

        }, networkUnavailableSampleImpl());
    }

    /*广播*/

    private void syncPhotoStart() {
        Intent intent = new Intent();
        intent.setAction(Config.ACTION_SYNC_TIMELINE_PHOTO_START);
        sendBroadcast(intent);
    }

    private void syncPhotoSuccess(String uuid, String url, String localThumbUrl, int number) {
        Intent intent = new Intent();
        intent.setAction(Config.ACTION_SYNC_TIMELINE_PHOTO_SUCCESS);
        intent.putExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_PHOTO_SUCCESS_UUID, uuid);
        intent.putExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_PHOTO_SUCCESS_URL, url);
        intent.putExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_PHOTO_SUCCESS_LOCAL_THUMB_URL, localThumbUrl);
        intent.putExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_PHOTO_SUCCESS_NUMBER, number);
        sendBroadcast(intent);
    }

    private void syncPhotoFailure(String value) {
        Intent intent = new Intent();
        intent.setAction(Config.ACTION_SYNC_TIMELINE_PHOTO_FAILURE);
        intent.putExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_PHOTO_FAILURE_MESSAGE, value);
        sendBroadcast(intent);
    }

    private void syncAudioStart() {
        Intent intent = new Intent();
        intent.setAction(Config.ACTION_SYNC_TIMELINE_AUDIO_START);
        sendBroadcast(intent);
    }

    private void syncAudioSuccess(String uuid, String url, String localUrl) {
        Intent intent = new Intent();
        intent.setAction(Config.ACTION_SYNC_TIMELINE_AUDIO_SUCCESS);
        intent.putExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_AUDIO_SUCCESS_UUID, uuid);
        intent.putExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_AUDIO_SUCCESS_URL, url);
        intent.putExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_AUDIO_SUCCESS_LOCAL_URL, localUrl);
        sendBroadcast(intent);
    }

    private void syncAudioFailure(String value) {
        Intent intent = new Intent();
        intent.setAction(Config.ACTION_SYNC_TIMELINE_AUDIO_FAILURE);
        intent.putExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_AUDIO_FAILURE_MESSAGE, value);
        sendBroadcast(intent);
    }

    private void syncVideoScreenshotStart() {
        Intent intent = new Intent();
        intent.setAction(Config.ACTION_SYNC_TIMELINE_VIDEO_SCREENSHOT_START);
        sendBroadcast(intent);
    }

    private void syncVideoScreenshotSuccess(String uuid, String url, String localUrl) {
        Intent intent = new Intent();
        intent.setAction(Config.ACTION_SYNC_TIMELINE_VIDEO_SCREENSHOT_SUCCESS);
        intent.putExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_VIDEO_SCREENSHOT_SUCCESS_UUID, uuid);
        intent.putExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_VIDEO_SCREENSHOT_SUCCESS_URL, url);
        intent.putExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_VIDEO_SCREENSHOT_SUCCESS_LOCAL_URL, localUrl);
        sendBroadcast(intent);
    }

    private void syncVideoScreenshotFailure(String value) {
        Intent intent = new Intent();
        intent.setAction(Config.ACTION_SYNC_TIMELINE_VIDEO_SCREENSHOT_FAILURE);
        intent.putExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_VIDEO_SCREENSHOT_FAILURE_MESSAGE, value);
        sendBroadcast(intent);
    }

}
